﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Profile;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;
using Facade;
using System.Collections;
using System.Data;

namespace IronOne.SalesOne.SalesOneWeb.UserManagement
{
    public partial class SearchUsers : SOSecurityPage, IDataPage ,IntTest
    {
        private int pageNo = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                UCGrid1.styleList = new List<GridViewStyle> {
                new GridViewStyle{
                    ColumnId = "UserName",
                    ColumnHeader = "Login Id",
                    ColumnWidth = 170 },
                new GridViewStyle{
                    ColumnId = "Name",
                    ColumnHeader = "Name",
                    ColumnWidth = 200},                
                new GridViewStyle{
                    ColumnId = "LastUpBy",
                    ColumnHeader = "Last Updated By",
                    ColumnWidth = 170},
                new GridViewStyle{
                    ColumnId = "LastUpdateDate",
                    ColumnHeader = "Last Updated Date",
                    Align = "right",
                    ColumnWidth = 170}
                
            };

               
                string postCause = this.Page.Request.Params.Get("__EVENTTARGET");

                if (postCause == null)
                {
                    if (Session["SUsr"] != null)
                    {
                        Search(Session["SUsr"].ToString(), pageNo);
                        Session.Remove("SUsr");
                    }

                    
                }

                if (Session["uInSuc"] != null)
                {
                    if (Session["uInSuc"].Equals("1"))
                    {
                        MassageSummery("IIS401");
                    }
                    else if (Session["uInSuc"].Equals("0"))
                    {
                        MassageSummery("IIS502");

                    }
                    else
                    {
                        MassageSummery("IIS5" + Session["uInSuc"]);
                    }

                    Session.Remove("uInSuc");
                }

                //string[] but = new string[] { "btnView", "btnCreate", "btnUpdate", "btnDelete" };
                //UCGridButtons1.Buttons = but;

                //if(!Page.IsPostBack)
                //UCGridButtons1.SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));
            }
            catch (Exception)
            {
                
            }
            
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UserManagement/AddUser.aspx");
            Session["UserAc"] = "create";
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search(string.Empty,1);
            pageNo = 1;
        }


        public void Search(string sn,int page)
        {

            try
            {
                if (Session["userName"] != null)
                {
                    Session.Remove("userName"); 
                }


                string uName = string.Empty;
                string uId = string.Empty;


                if (string.IsNullOrEmpty(sn))
                {
                    uName = "%" + txtUserName.Text + "%";
                    uId = "%" + txtUserId.Text + "%";

                    if (page == 1)
                    {
                        UCGrid1.SetText("1");
                        Session["SUsr"] = txtUserName.Text;
                    }
                    
                }
                else
                {
                    uName = sn;
                }

                

                StructureFacade sFac = new StructureFacade();
                List<User> usrs = sFac.GetSearchUsers(uName, uId, page);
                if (usrs.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                {
                    UCGrid1.IsLastPage = (sFac.GetSearchUsers(uName, uId, page + 1)).Count > 0 ? false : true;
                }

                int[] hideArr = { 1,2,3,8,9,10,11,12,13,14,15,16,17,18,19,20 };
                //int[] hideArr = null;
                UCGrid1.SetDataSource(usrs, hideArr);
                
                
                
                
                
                
                
                
                
                
                
                
                //DataTable usrTable = new DataTable();
                //DataRow newRow;

                //usrTable.Columns.Add("Id");
                //usrTable.Columns.Add("Name");
                //usrTable.Columns.Add("Last Updated By");
                //usrTable.Columns.Add("Last Updated Date");

                //StructureFacade sFac = new StructureFacade();
                //foreach (SalesOne.BusinessObjects.User usr in sFac.GetSearchUsers(uName,uId, page))
                //{
                //    string lastUpBy = "";
                //    string updatedDate = "";
                //    string name = "";

                //    if (usr != null)
                //    {
                //        MembershipUser adUser = Membership.GetUser(usr.LastUpBy);
                //        MembershipUser u = Membership.GetUser(usr.UserName);

                //        lastUpBy = adUser.UserName;
                //        updatedDate = usr.LastUpdateDate.ToShortDateString();
                //        name = usr.Name;


                //        newRow = usrTable.NewRow();
                //        newRow[0] = usr.UserName;
                //        newRow[1] = name;
                //        newRow[2] = lastUpBy;
                //        newRow[3] = updatedDate;


                //        //if (u.IsApproved != false && u.IsLockedOut != true)
                //        //{
                //            usrTable.Rows.Add(newRow);
                //        //}
                //    }

                    

                //}




                

                //int[] hideArr = { 1 };
                //UCGrid1.SetDataSource(usrTable, hideArr);

                if (usrs.Count > 0)
                {
                    UCGridButtons1.SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));
                    btnDisable.Visible = true;
                    //lblRes.Text = "Result";
                    UCGridButtons1.Visible = true;
                }
                else
                {
                    //lblRes.Text = "";
                    UCGridButtons1.Visible = false;
                    btnDisable.Visible = false;
                    MassageSummery("IIS504");
                    //lblError.Text = "No users to display";
                }

                
            }
            catch (Exception ex)
            {

                Response.Write(ex.Message);
            }
        
        
        
        }



        public void View()
        {
            if (Session["userName"] == null)
            {

                Session["userName"] = ((GridViewRow)Session["firstRow"]).Cells[4].Text;
                Session.Remove("firstRow");
            }

            if (Session["userName"] != null)
            {
                Response.Redirect("~/UserManagement/ViewUser.aspx");
            }
            else
            {
                MassageSummery("IIS503");
                //lblError.Text = "Please select a user";
            }
        }

        public void Create()
        {

                Response.Redirect("~/UserManagement/AddUser.aspx");
            
           
        }

        public void Update()
        {
            if (Session["userName"] == null)
            {
                if (Session["firstRow"] != null)
                {
                    Session["userName"] = ((GridViewRow)Session["firstRow"]).Cells[4].Text;
                    Session.Remove("firstRow");
                }
                else
                {
                    MassageSummery("IIS503");
                }
                
            }

            if (Session["userName"] != null)
            {
            Response.Redirect("~/UserManagement/UpdateUser.aspx");
            }
            else
            {
                MassageSummery("IIS503");
            }
        }

        public void Delete()
        {

            try
            {
                if (Session["userName"] == null)
                {

                    Session["userName"] = ((GridViewRow)Session["firstRow"]).Cells[4].Text;
                    Session.Remove("firstRow");
                }



                if (Session["userName"] != null)
                {
                    int[] numbers = { 1 };
                    string user = Session["userName"].ToString();
                    MembershipUser usr = Membership.GetUser(user);
                    Guid userGuuid = (Guid)usr.ProviderUserKey;


                    StructureFacade StructureFacade = new StructureFacade();

                    User usrObj = StructureFacade.GetUser(userGuuid);
                    usrObj.Country = "1";
                    usrObj.IdType = "1";


                    UserInformation info = StructureFacade.GetUserInformation(Session["userName"].ToString());


                    int success = 0;
                    usrObj.IsDeleted = true;
                    success = StructureFacade.UpdateUser(usrObj);

                    if (success == 1)
                    {
                        Search(Session["SUsr"].ToString(), pageNo);
                        MassageSummery("IIS401");

                    }
                    else
                    {
                        MassageSummery("IIS502");

                    }

                    Session.Remove("userName");


                }
                else
                {
                    MassageSummery("IIS503");

                }


            }
            catch (Exception)
            {

            }


            //try
            //{
            //    if (Session["userName"] == null)
            //    {

            //        Session["userName"] = ((GridViewRow)Session["firstRow"]).Cells[2].Text;
            //        Session.Remove("firstRow");
            //    }



            //    if (Session["userName"] != null)
            //    {
            //        int[] numbers = { 1 };
            //        string user = Session["userName"].ToString();
            //        MembershipUser usr = Membership.GetUser(user);
            //        Guid userGuuid = (Guid)usr.ProviderUserKey;


            //        StructureFacade StructureFacade = new StructureFacade();

            //        User usrObj = StructureFacade.GetUser(userGuuid);
            //        usrObj.Country = "1";
            //        usrObj.IdType = "1";


            //        UserInformation info = StructureFacade.GetUserInformation(Session["userName"].ToString());


            //        int success = 0;
            //        success = StructureFacade.DeleteUser(usrObj);
            //        if (success == 1)
            //        {
            //            bool f = Membership.DeleteUser(usr.UserName, true);
            //            if (f == true)
            //            {

            //                //lblSuccess.Text = "Successfully deleted user " + usr.UserName;
            //                Search(Session["SUsr"].ToString(), pageNo);
            //                MassageSummery("IIS401");
            //            }

            //        }
            //        else
            //        {
            //            MassageSummery("IIS502");
            //            //lblError.Text = "Fail to delete user";
            //        }

            //        Session.Remove("userName");


            //    }
            //    else
            //    {
            //        MassageSummery("IIS503");
            //        //lblError.Text = "Please select a user";
            //    }


            //}
            //catch (Exception)
            //{

            //}
            

        }

        public void Cancel()
        {

        }



        #region IDataPage Members


        public void GetId(GridViewRow row)
        {
            //Updated on 19 Feb 2010 By Sajith.
            //User id is in 4th cell.
            //Session["userName"] = row.Cells[3].Text;
            Session["userName"] = row.Cells[4].Text;
        }

        #endregion

        protected void btnDisable_Click(object sender, EventArgs e)
        {

            try
            {
                if (Session["userName"] == null)
                {
                    if (Session["firstRow"] != null)
                    {
                        Session["userName"] = ((GridViewRow)Session["firstRow"]).Cells[3].Text;
                        Session.Remove("firstRow");
                    }
                    else
                    {
                        MassageSummery("IIS503");
                    }
                    
                }

                if (Session["userName"] != null)
                {
                    MembershipUser usr = Membership.GetUser(Session["userName"].ToString());
                    usr.IsApproved = false;
                    Membership.UpdateUser(usr);

                    MassageSummery("IIS406");
                    //lblSuccess.Text = "User " + Session["userName"] + " was successfully disabled.";
                    Session.Remove("userName");


                    if (Session["SUsr"] != null)
                    {
                        Search(Session["SUsr"].ToString(), pageNo);
                    }
                    else
                    {
                        Search(string.Empty, pageNo);
                    }


                }
                else
                {
                    MassageSummery("IIS503");

                }
            }
            catch (Exception)
            {
                MassageSummery("IIS502");
            }
            
        }

        #region IntTest Members

        public void Next()
        {
            if (UCGrid1.GetText() != "1")
            {
                pageNo = Convert.ToInt32(UCGrid1.GetText()) + 1;
                UCGrid1.SetText(pageNo.ToString());

            }
            else
            {
                pageNo = 2;
                UCGrid1.SetText("2");

            }

            Search(string.Empty, pageNo);
        }

        public void Previous()
        {

            if (UCGrid1.GetText() != "1")
            {
                pageNo = Convert.ToInt32(UCGrid1.GetText()) - 1;
                UCGrid1.SetText(pageNo.ToString());

                Search(string.Empty, pageNo);
            }
        }

        public void Go()
        {

            int p = int.Parse(UCGrid1.GetText());
            if (p != 0)
            {
                try
                {
                    Search(Session["SUsr"].ToString(), p);
                    pageNo = p;
                }
                catch (Exception)
                {

                    throw;
                }


            }
        }

        #endregion
    }
}
